﻿using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System;

namespace JasonTools
{
    public static class ImageExtension
    {
        public static void ReleaseCache(this Image image)
        {
            if (image == null)
            {
                return;
            }

            BitmapImage bitmapImage = image.Source as BitmapImage;
            if (bitmapImage != null)
            {
                image.Tag = bitmapImage.UriSource.OriginalString;
                bitmapImage.UriSource = null;
                image.Source = null;
            }
        }

        public static void ReattachSource(this Image image)
        {
            if (image == null)
            {
                return;
            }

            if (image.Tag != null)
            {
                Uri uri = new Uri(image.Tag.ToString(), UriKind.Relative);
                BitmapImage bitmapImage = new BitmapImage(uri);
                image.Source = bitmapImage;
                image.UpdateLayout();
            }
        }
    }
}
